<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket Demo</title>
    <script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
    <script type="text/javascript">
        let webSocket = null;

        if ('WebSocket' in window) {
            webSocket = new WebSocket("ws://127.0.0.1:9002/ws");
        } else {
            console.log('webSocket not support')
        }

        webSocket.onopen = function () {
            show("已连接");
        };

        webSocket.onmessage = function (event) {
            $('#message').append('<div class="ms">' + event.data + '</div>')
        };

        webSocket.onclose = function () {
            show("已关闭");
        };

        //连接发生错误的回调方法
        webSocket.onerror = function () {
            show("连接错误");
        };

        function closeWebSocket() {
            webSocket.close();
        }

        function show(innerHTML) {
            document.getElementById('status').innerHTML = innerHTML;
        }

        function send() {
            let message = document.getElementById('ta').value;
            webSocket.send(message);
            document.getElementById('ta').value = '';
        }

        window.onbeforeunload = function () {
            webSocket.close();
        };

    </script>

</head>
<body>


<div class="container" style="padding: 20px">
    <div class="status">
        连接状态：<span id="status">未连接</span>
        <a href="javascript:void(0)" onclick="closeWebSocket()">关闭连接</a>
    </div>
    <hr>
    <div id="message" style="min-height: 200px; margin: 20px 0 10px">

    </div>
    <hr>
    <div class="text">
        <textarea name="" id="ta" cols="60" rows="4"></textarea>
        <br>
        <button onclick="send()">发送</button>
    </div>
</div>

</body>
</html>